package com.lq.learningTest.duoxiancheng;

public class Wait {
    public static final Object lock = new Object();

    public static void main(String[] args) {
        //持有锁，等待
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    System.out.println("线程一开始了");
                    try {
                        lock.wait();//等待了就会释放这个锁的cpu资源，而sleep不会释放锁的资源，所以当这个锁wait的时候，其他的线程是能够抢到这把锁的
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println("线程一结束了");
                }
            }
        }).start();

        //请求锁，唤醒
        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {//持有哪把锁，才能够对哪把锁进行操作
                    System.out.println("线程二开始了");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    lock.notify();//把wait的哪个线程唤醒
                    System.out.println("线程二结束了");
                }
            }
        }).start();
    }
}
